package com.commerceerp.system.service;

import com.commerceerp.system.api.amazon.client.MwsUtl;
import com.commerceerp.system.api.amazon.orders._2013_09_01.MarketplaceWebServiceOrdersAsyncClient;
import com.commerceerp.system.api.amazon.orders._2013_09_01.MarketplaceWebServiceOrdersClient;
import com.commerceerp.system.api.amazon.orders._2013_09_01.MarketplaceWebServiceOrdersConfig;
import com.commerceerp.system.api.amazon.orders._2013_09_01.model.ListOrdersRequest;
import com.commerceerp.system.api.amazon.orders._2013_09_01.model.ListOrdersResponse;
import com.commerceerp.system.api.amazon.orders._2013_09_01.samples.ListOrdersSample;
import com.commerceerp.system.entity.*;
import com.commerceerp.system.mapper.ShopMapper;
import com.commerceerp.system.util.ApiResult;
import com.commerceerp.system.util.DateUtil;
import com.commerceerp.system.util.StringUtils;
import com.ebay.sdk.*;
import com.ebay.sdk.call.FetchTokenCall;
import com.ebay.sdk.call.GetSessionIDCall;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.xml.datatype.XMLGregorianCalendar;
import java.io.IOException;
import java.util.*;

/**
 * Created by Administrator on 2018/6/11/011.
 */
@Service
public class ShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Value("${ebay.appID}")
    private String ebayAppID;

    @Value("${ebay.devID}")
    private String ebayDevID;

    @Value("${ebay.certID}")
    private String ebayCertID;

    @Value("${ebay.ruName}")
    private String ebayRuName;

    //wish店铺
    public ApiResult wishFindList(String userId) {
        //获得wish店铺
        return new ApiResult(shopMapper.wishFindList(userId));
    }

    //wish店铺编辑
    public ApiResult formWish(ShopWish shopWish) {
        ShopWish check = shopMapper.getShopWishByClientId(shopWish.getClientId());
        if (check != null) {
            if (StringUtils.isEmpty(shopWish.getId())) {
                return new ApiResult(405, "该账号已经被" + check.getShopName() + "添加");
            }
            if (StringUtils.isNotEmpty(shopWish.getId()) && !StringUtils.equals(shopWish.getId(), check.getId())) {
                return new ApiResult(405, "该账号已经被" + check.getShopName() + "添加");
            }
        }
        if (StringUtils.isEmpty(shopWish.getId())) {//添加
            shopWish.setDelFlag("1");
            shopWish.insert();
            shopWish.setDelFlag("1");
            //防止旧的账号存在，删除已经
            shopMapper.delWishByClientId(shopWish.getClientId());
            shopMapper.insertWisth(shopWish);
        } else {//编辑
            shopWish.update();
            shopMapper.updateWish(shopWish);
        }
        return new ApiResult(200, "编辑成功");
    }

    //wish店铺删除
    public ApiResult delWish(String id, String userId) {
        if (shopMapper.delWish(id, userId) > 0) {
            return new ApiResult(200, "删除成功");
        }
        return new ApiResult(405, "删除失败");
    }

    //Amazon店铺
    public ApiResult amazonFindList(String userId) {
        //获得wish店铺
        return new ApiResult(shopMapper.amazonFindList(userId));
    }

    //Amazon店铺编辑
    public ApiResult formAmazon(ShopAmazon shopAmazon) {
        //检查店铺是否存在
        if (shopMapper.getShopAmazon(shopAmazon) != null) {
            return new ApiResult(405, "该账号已被添加");
        }
        Map amazonEndpoint = shopMapper.getAmazonEndpoint(shopAmazon.getAccountWeb());
        if(amazonEndpoint == null){
            return new ApiResult(405, "开户站信息有误");
        }
        String serviceURL = (String)amazonEndpoint.get("endpoint");
        String marketplaceId = (String)amazonEndpoint.get("marketplaceId");

        String accessKey = shopAmazon.getAwsAccessKeyId();
        String secretKey = shopAmazon.getSecretKey();
        String appName = "erp";
        String appVersion = "2";
        String sellerId = shopAmazon.getMerchantId();
        MarketplaceWebServiceOrdersConfig config = new MarketplaceWebServiceOrdersConfig();
        config.setServiceURL(serviceURL);
        MarketplaceWebServiceOrdersClient client = new MarketplaceWebServiceOrdersAsyncClient(accessKey, secretKey,
                appName, appVersion, config, null);
        ListOrdersRequest request = new ListOrdersRequest();
        request.setSellerId(sellerId);
        XMLGregorianCalendar createdAfter = MwsUtl.getDTF().newXMLGregorianCalendar();
        createdAfter.setYear(2018);
        createdAfter.setMonth(1);
        createdAfter.setDay(1);
        createdAfter.setTime(0, 0, 0);
        request.setCreatedAfter(createdAfter);
        List<String> marketplaceIds = new ArrayList<String>();
        marketplaceIds.add(marketplaceId);
        request.setMarketplaceId(marketplaceIds);
        Integer maxResultsPerPage = 100;
        request.setMaxResultsPerPage(maxResultsPerPage);
        List<String> tfmShipmentStatus = new ArrayList<String>();
        request.setTFMShipmentStatus(tfmShipmentStatus);
        try {
            ListOrdersResponse response = ListOrdersSample.invokeListOrders(client, request);
        if (StringUtils.isEmpty(shopAmazon.getId())) {//添加
            shopAmazon.insert();
            shopMapper.insertAmazon(shopAmazon);
        } else {//编辑
            shopAmazon.update();
            shopMapper.updateAmazon(shopAmazon);
        }
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(405, "授权失败");
        }
        return new ApiResult(200, "编辑成功");
    }

    //Amazon店铺删除
    public ApiResult delAmazon(String id, String userId) {
        if (shopMapper.delAmazon(id, userId) > 0) {
            return new ApiResult(200, "删除成功");
        }
        return new ApiResult(405, "删除失败");

    }

    //Amazon端点
    public ApiResult amazonEndpoint() {

        return new ApiResult(shopMapper.amazonEndpoint());
    }

    //ebay店铺创建
    public ApiResult formEbay(ShopEbay shopEbay) {
        /*
         * 生成Context
         */
        ApiContext localContext = new ApiContext();
        ApiAccount apiAccount = new ApiAccount();
        apiAccount.setApplication(ebayAppID);
        apiAccount.setCertificate(ebayCertID);
        apiAccount.setDeveloper(ebayDevID);
        localContext.getApiCredential().setApiAccount(apiAccount);
        localContext.setApiServerUrl("https://api.ebay.com/wsapi");

        /*
         *获取SessionID和生成登录URL
         */
        GetSessionIDCall apiCall = new GetSessionIDCall(localContext);
        apiCall.setRuName(ebayRuName);
        String sessionID = null;
        try {
            sessionID = apiCall.getSessionID();
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(405, "生成sessionID异常");
        }
        //保存店铺
        shopEbay.setSessionId(sessionID);
        shopEbay.insert();
        shopEbay.setDelFlag("1");
        shopMapper.insertEbay(shopEbay);

        //沙箱环境的连接，正式的时候可能要换连接
        String url = "https://www.ebay.com/ws/eBayISAPI.dll?SignIn&runame=" + ebayRuName + "&SessID=" + sessionID;
        Map map = new HashMap();
        map.put("url", url);
        map.put("sessionID", sessionID);
        return new ApiResult(200, map, "返回sessionID");
    }

    //验证ebay门店是否授权
    public ApiResult vailCode(String sessionID) {
        /*
         * 生成Context
         */
        ApiContext localContext = new ApiContext();
        ApiAccount apiAccount = new ApiAccount();
        apiAccount.setApplication(ebayAppID);
        apiAccount.setCertificate(ebayCertID);
        apiAccount.setDeveloper(ebayDevID);
        localContext.getApiCredential().setApiAccount(apiAccount);
        localContext.setApiServerUrl("https://api.ebay.com/wsapi");
        /*
         *生成token
         */
        FetchTokenCall fetchTokenCall = new FetchTokenCall(localContext);
        fetchTokenCall.setSessionID(sessionID);
        String token = null;
        try {
            token = fetchTokenCall.fetchToken();
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(405, "授权失败");
        }
        System.out.println("token :" + token);
        ShopEbay shopEbay = shopMapper.getShopEbayBySessionId(sessionID);
        shopEbay.setToken(token);
        shopEbay.setEffectiveTime(DateUtil.getAfterDate(DateUtil.getYMDHMSDate(),30*18));
        shopEbay.setDelFlag("0");
        shopEbay.update();
        shopMapper.updateEbay(shopEbay);
        return new ApiResult(200, "授权成功");
    }

    /**
     * 生成APIContext
     *
     * @return
     * @throws IOException
     */
    // Initializes ApiContext with token and eBay API server URL
    public ApiContext getApiContext(String token) {
        ApiContext apiContext = new ApiContext();
        ApiAccount apiAccount = new ApiAccount();
        apiAccount.setApplication(ebayAppID);
        apiAccount.setCertificate(ebayCertID);
        apiAccount.setDeveloper(ebayDevID);
        apiContext.getApiCredential().setApiAccount(apiAccount);
        ApiCredential cred = apiContext.getApiCredential();
        cred.seteBayToken(token);
        apiContext.setApiServerUrl("https://api.ebay.com/wsapi");
        apiContext.setEpsServerUrl("https://api.ebay.com/ws/api.dll");    // 这个要设置，不然会出错
        return apiContext;
    }

    //ebay店铺
    public ApiResult ebayFindList(String userId) {

        return new ApiResult(shopMapper.getShopEbayById(null, userId));
    }

    //ebay店铺删除
    public ApiResult delEbay(String id, String userId) {
        if (shopMapper.delEbay(id, userId) > 0) {
            return new ApiResult(200, "删除成功");
        }
        return new ApiResult(405, "删除失败");
    }

}
